package com.ljh.cloudmusic.service;

import com.ljh.cloudmusic.mapper.LoveMusicMapper;
import com.ljh.cloudmusic.mapper.UserMapper;
import com.ljh.cloudmusic.model.LoveMusic;
import com.ljh.cloudmusic.model.User;
import com.ljh.cloudmusic.utils.JwtUtils;
import com.ljh.cloudmusic.utils.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: Themberfue
 * @date: 2025/3/9 23:15
 * @description:
 */
@Service
public class LoveMusicService {
    @Value("${music.local.path}")
    private static String SAVE_PATH;

    @Autowired
    LoveMusicMapper loveMusicMapper;

    @Autowired
    UserMapper userMapper;

    public ResponseBodyMessage<Boolean> likeMusic(Integer musicId, HttpServletRequest request) {
        // TODO 获取 Authorization 头部
        String token = request.getHeader("Authorization");

        // TODO 检查 Token 是否有效
        if (token == null || !token.startsWith("Bearer ")) {
            return new ResponseBodyMessage<>(-1, "搜索音乐失败，请登录后重试", null);
        }
        // TODO 去掉 "Bearer " 部分
        token = token.substring(7);

        // TODO 从 Token 解析出 username，从数据库查询 user
        User user = userMapper.selectLoginByUsername(JwtUtils.getUsernameFromToken(token));
        Integer userId = user.getId();

        String createTime = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        // TODO 在数据库中查找该歌曲
        LoveMusic loveMusic = loveMusicMapper.selectSingleLoveMusic(userId, musicId);
        if (loveMusic == null) {
            loveMusicMapper.insertLoveMusic(userId, musicId, createTime);
            return new ResponseBodyMessage<>(0, "收藏音乐成功", true);
        } else if (!loveMusic.isFavorite()) {
            loveMusicMapper.updateLoveMusic(userId, musicId, 1);
            return new ResponseBodyMessage<>(0, "收藏音乐成功", true);
        } else {
            loveMusicMapper.updateLoveMusic(userId, musicId, 0);
            return new ResponseBodyMessage<>(0, "从收藏音乐中移除成功", true);
        }
    }
}
